package lium.lbs.lbsim;


import android.os.Bundle;
import android.support.annotation.DrawableRes;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.lmlibrary.Constants;
import com.lmlibrary.base.DemoCallback;
import com.lmlibrary.bean.ResponseBean;
import com.lmlibrary.exception.MyException;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.PostRequest;
import com.lzy.okgo.utils.OkLogger;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import lium.lbs.lbsim.base.BaseParamMap;
import lium.lbs.lbsim.utils.ToastUtils;

import java.io.File;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public abstract class OBaseActivity extends FragmentActivity {


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    public void displayImageFile(File file, ImageView imageView) {
        Glide.with(getApplicationContext()).load(file).into(imageView);
    }

    public void displayImageFile(File file, ImageView imageView, @DrawableRes int errorImage) {
        RequestOptions options = new RequestOptions();
        options.placeholder(errorImage);
        Glide.with(getApplicationContext()).load(file).apply(options).into(imageView);
    }

    public void displayImage(String url, ImageView imageView) {
        Glide.with(getApplicationContext())
                .load(url)
                .into(imageView);
    }

    public void displayImage(String url, @DrawableRes int errorImage, ImageView imageView) {
        RequestOptions options = new RequestOptions();
        options.placeholder(errorImage);
        Glide.with(getApplicationContext())
                .load(url)
                .apply(options)
                .into(imageView);
    }

    public <T> void handleError(Response<T> response) {
        if (response == null) return;
        if (response.getException() != null) response.getException().printStackTrace();
        int code = response.code();
        if (code == 404) {
            Log.d("JsonCallback", "404 当前链接不存在");
        }
        Throwable exception = response.getException();
        if (response.getException() instanceof SocketTimeoutException) {
            Log.d("JsonCallback", "请求超时");
        } else if (response.getException() instanceof SocketException) {
            Log.d("JsonCallback", "服务器异常");
        } else if (response.getException() instanceof MyException) { //个人自定义 异常 根据后台 约定值判断异常雷系
            switch (((MyException) response.getException()).getErrorBean().status) {
                case 1://约定的数据错误
                    ToastUtils.showToast(((MyException) response.getException()).getErrorBean().msg);
                    break;
                default:
                    ToastUtils.showToast(((MyException) response.getException()).getErrorBean().msg);
                    break;
            }

        }
    }


    int time = 1;

    /**
     * 模拟假数据
     * 倒计时3秒
     */
    public void postFakeData(final DemoCallback demoCallBack) {
        Observable.interval(1, TimeUnit.SECONDS)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(@NonNull Long aLong) throws Exception {
                        return time - aLong;
                    }
                })
                .take(time + 1)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnComplete(new Action() {
                    @Override
                    public void run() throws Exception {
                        demoCallBack.onSuccess();
                    }
                })
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long aLong) throws Exception {

                    }
                });
    }

    public <T> void postData(String url, HashMap paramMap, Callback<T> callback) {
        BaseParamMap m = new BaseParamMap();
        m.putAll(paramMap);
        String paramJson = new Gson().toJson(m);
        OkLogger.e("接口--" + url + "--参数:--" + paramJson + "--body");
        PostRequest postRequest = OkGo.<ResponseBean<T>>post(Constants.Host + url)//
                .tag(this)
                .isMultipart(true); //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
        postRequest.getParams().put(m);
        postRequest.execute(callback);
    }

    public <T> void postDataOut(String url, HashMap paramMap, Callback<T> callback) {
        BaseParamMap m = new BaseParamMap();
        m.putAll(paramMap);
        String paramJson = new Gson().toJson(m);
        OkLogger.e("接口--" + url + "--参数:--" + paramJson + "--body");
        PostRequest postRequest = OkGo.<ResponseBean<T>>post(url)//
                .tag(this)
                .isMultipart(true); //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
        postRequest.getParams().put(m);
        postRequest.execute(callback);
    }

    public <T> void postDataWithFile(String url, String imageKey, HashMap paramMap, File file, Callback<T> callback) {
        BaseParamMap m = new BaseParamMap();
        m.putAll(paramMap);
        PostRequest postRequest = OkGo.<ResponseBean<T>>post(Constants.Host + url)//
                .tag(this)
                .isMultipart(true); //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
        postRequest.getParams().put(m);
        postRequest.getParams().put(imageKey, file);
        // postRequest.getParams().putFileParams(imageKey,fileList);
        postRequest.execute(callback);
    }

    public <T> void postDataWithFile(String url, HashMap<String, File> fileMap, HashMap paramMap, Callback<T> callback) {
        BaseParamMap m = new BaseParamMap();
        m.putAll(paramMap);
        PostRequest postRequest = OkGo.<ResponseBean<T>>post(Constants.Host + url)//
                .tag(this)
                .isMultipart(true); //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
        postRequest.getParams().put(m);
        if (fileMap != null && fileMap.size() > 0) {
            for (Map.Entry<String, File> entry : fileMap.entrySet()) {
                postRequest.params(entry.getKey(), entry.getValue(), entry.getValue().getName());
            }
        }
        // postRequest.getParams().putFileParams(imageKey,fileList);
        postRequest.execute(callback);
    }


    public <T> void postDataWithFiles(String url, HashMap paramMap, String imageKey, ArrayList<File> fileList, Callback<T> callback) {
        BaseParamMap m = new BaseParamMap();
        m.putAll(paramMap);
        PostRequest postRequest = OkGo.<ResponseBean<T>>post(Constants.Host + url)//
                .tag(this)
                .isMultipart(true); //强制使用 multipart/form-data 表单上传（只是演示，不需要的话不要设置。默认就是false）
        postRequest.getParams().put(m);
        if (fileList != null && fileList.size() > 0) {
            for (int i = 0; i < fileList.size(); i++) {
                postRequest.getParams().put(imageKey + "[" + i + "]", fileList.get(i), fileList.get(i).getName());
            }
        }
        postRequest.execute(callback);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    private long exitTime = 0;


}
